package network

import (
	"context"
	"fmt"
	"github.com/scaleway/scaleway-sdk-go/api/lb/v1"
	"time"

	"github.com/scaleway/scaleway-sdk-go/scw"
	log "github.com/sirupsen/logrus"

	"github.com/tailwarden/komiser/models"
	"github.com/tailwarden/komiser/providers"
)

func LoadBalancers(ctx context.Context, client providers.ProviderClient) ([]models.Resource, error) {
	resources := make([]models.Resource, 0)

	lbSvc := lb.NewAPI(client.ScalewayClient)

	regions := []scw.Region{scw.RegionFrPar, scw.RegionNlAms, scw.RegionPlWaw}

	for _, region := range regions {
		output, err := lbSvc.ListLBs(&lb.ListLBsRequest{
			Region: region,
		})
		if err != nil {
			return resources, err
		}
		for _, loadBalancer := range output.LBs {
			resources = append(resources, models.Resource{
				Provider:   "Scaleway",
				Account:    client.Name,
				Service:    "LoadBalancer",
				Region:     loadBalancer.Zone.String(),
				ResourceId: loadBalancer.ID,
				// loadBalancer.Tags is a slice of strings so, we can't extract them in key and value pair.
				//Tags:       loadBalancer.Tags,
				Name:      loadBalancer.Name,
				FetchedAt: time.Now(),
				Link:      fmt.Sprintf("https://console.scaleway.com/load-balancer/lbs/%s/%s", loadBalancer.Zone.String(), loadBalancer.ID),
			})
		}
	}
	log.WithFields(log.Fields{
		"provider":  "Scaleway",
		"account":   client.Name,
		"service":   "LoadBalancer",
		"resources": len(resources),
	}).Info("Fetched resources")
	return resources, nil
}
